package com.ljg.activiti.i_start;

import java.io.InputStream;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 流程开始活动测试类
 * @author guo
 *
 */
public class StartTest {

	private Logger log = LoggerFactory.getLogger(StartTest.class);
	
	// 流程引擎对象
	private ProcessEngine processEngine;
	
	@Before
	public void before() {
		/**
		 * 创建默认的流程引擎对象，默认读取classpath下的activiti.cfg.xml创建流程引擎对象
		 */
		processEngine = ProcessEngines.getDefaultProcessEngine();
		log.info("创建流程引擎对象成功！");
	}
	
	/**
	 * 部署流程定义-从inputstream
	 *  processEngine.getRepositoryService()：获取流程定义和流程部署相关的Service
	 */
	@Test
	public void deploymentProcessDefinition_inputstream() {
		InputStream bpmnIn = this.getClass().getClassLoader().getResourceAsStream("diagrams/StartProcess.bpmn");
		InputStream pngIn = this.getClass().getClassLoader().getResourceAsStream("diagrams/StartProcess.png");
		Deployment deployment = processEngine.getRepositoryService() // 获取流程定义和流程部署相关的Service
			.createDeployment() // 创建流程部署对象
			.addInputStream("StartProcess.bpmn", bpmnIn) // 从InputStream中加载流程资源
			.addInputStream("StartProcess.png", pngIn) // 
			.name("开始活动测试流程") // 添加部署的名称
			.deploy();
		
		log.info("部署完成，deploymentId=" + deployment.getId() + "，deploymentName=" + deployment.getName() + "，deploymentTime=" + deployment.getDeploymentTime());
	}
	
	/**
	 * 启动流程实例，判断流程是否结束，查询流程历史
	 * processEngine.getRuntimeService() // 获得正在执行的流程实例和执行对象相关的Service
	 */
	@Test
	public void startProcessInstance() {
		String processDefinitionKey = "StartProcess"; // 流程定义的key对应bpmn文件中id的属性值
		ProcessInstance pi = processEngine.getRuntimeService() // 获得与正在执行的流程实例和执行对象相关的Service
			.startProcessInstanceByKey(processDefinitionKey); // 根据流程定义的key启动流程实例，默认是按照最新版本的流程定义启动
		log.info("启动流程成功，Id=" + pi.getId() + "，deploymentId=" + pi.getDeploymentId() + "，name=" + pi.getName() + "，processInstanceId=" + pi.getProcessInstanceId());
		
		// 判断流程是否结束，查询正在执行的执行对象表
		ProcessInstance rpi = processEngine.getRuntimeService() // 
			.createProcessInstanceQuery() // 创建流程实例查询对象
			.processInstanceId(pi.getId()) // 根据流程实例查询
			.singleResult();
		
		if(rpi == null) { // 说明流程已经结束
			// 查询流程历史
			HistoricProcessInstance hpi = processEngine.getHistoryService()//
				.createHistoricProcessInstanceQuery() // 历史流程实例查询
				.processInstanceId(pi.getId()) // 根据流程实例Id查询
				.singleResult();
			log.info("历史流程实例查询 ---> " + hpi.getId() + "---" + hpi.getStartTime() + "---" + hpi.getEndTime());
		}
	}
	
}
